import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_first_project/api/login.dart';
import 'package:flutter_first_project/utils/Emitter.dart';
import 'package:flutter_first_project/utils/TokenManager.dart';
import 'package:flutter_first_project/utils/toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Timer? _timer; //定时器
  int _count = 60; // 倒计时
final TextEditingController _phoneController = TextEditingController(); // 手机号
 final TextEditingController _codeController = TextEditingController(); // 验证码

//验证手机号并发送请求获取验证码
      _sendCode() async{
        if(_count == 60){
          // 验证手机号
          if(_phoneController.text.isEmpty){
           return PrompAction.showFales('请输入手机号');
          }
          // RegExp reg = RegExp(r'^1[3-9]\d{9}$');
          RegExp reg = RegExp(r'^1[3-9]\d{9}$');
          if(!reg.hasMatch(_phoneController.text)){
           return PrompAction.showFales('请输入正确的手机号');
          }
          // 防止用户重复点击
           setState(() {
        _count--;
      });
             beginCount(); // 开始倒计时
             final res = await sendCodeAPI({'mobile':  _phoneController.text});
             Future .delayed(const Duration(seconds: 1),(){
              _codeController.text = res['code'];
              // setState(() {});
             });
        }
      }

// 开启倒计时
  beginCount(){
      _timer = Timer.periodic(const Duration(seconds: 1), (timer){
        if(_count == 0){
          _timer?.cancel(); // 取消定时器
          _count = 60; // 重置倒计时
        }
        else{
          if(_count < 60){
            _count--;
          }
        }
        setState(() {});
      });
  }

  // 获取倒计时显示
Widget getTimerShow(){
    if(_count == 60){
      return const Text('获取验证码');
    }
    else{
      return Text('$_count秒后获取');
    }

  }


void _login() async{
  // PrompAction.showInfo(_phoneController.text);
  // 校验手机号和验证码
  if(_phoneController.text.isEmpty || _codeController.text.isEmpty){
   PrompAction.showFales('手机号和验证码不能为空');
    return;
  }
  // 正则校验
  RegExp reg = RegExp(r'^1[3-9]\d{9}$'); //手机号正则
  RegExp  codeReg = RegExp(r'^\d{6}$');  // 验证码正则
  if(!reg.hasMatch(_phoneController.text) || !codeReg.hasMatch(_codeController.text)){
    PrompAction.showFales('手机号和验证码格式不正确');
  }
  //  发送请求
  var res=await loginAPI({'mobile': _phoneController.text, 'code': _codeController.text});
  tokenManager.setToken(res['token'],refreshToken: res['refreshToken']); //  保存token
  // 关闭定时器
  _timer?.cancel();
  Navigator.pop(context); // 关闭当前页面

  // 通知我的页面进行数据的获取
    eventBus.fire(LogSuccessEvent());
}
@override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // 页面离开时销毁定时器
    _timer?.cancel();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                 Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration:const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    // 倒计时
                    _sendCode();
                  },
                  child: getTimerShow(),
                ),
              ],
            ),
            const SizedBox(height: 8),
             TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
